package mapgen {
import kgame5.kutil.RecordStore;

import mapgen.func.MapDataReader;
import mapgen.func.MapDataWriter;
import mapgen.pane.MyPane;

import org.aswing.ASColor;
import org.aswing.event.AWEvent;

import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.system.System;

/**
 * @author kangkai
 */
[SWF(width="1000",height="600",backgroundColor="0x000000",frameRate="20")]

public class MapGen extends Sprite {
	private var pane : MyPane;
	
	private var writer:MapDataWriter=new MapDataWriter();
	private var reader:MapDataReader=new MapDataReader();
	
	public function MapGen() {
		
		RecordStore.open("MapGen");
		
		pane = new MyPane();
		this.addChild(pane);
		pane.setBackground(ASColor.LIGHT_GRAY);
		pane.validate();
		
		pane.getBtn().addActionListener(onClickWrite);
		
		if(RecordStore.getData("fileUrlSWF")!=null){
			pane.getTf().setText(RecordStore.getData("fileUrlSWF")+"");
		}else{
			pane.getTf().setText("mapswf\4.swf");
		}
		
		pane.getBtnIn().addActionListener(onClickRead);
		if(RecordStore.getData("fileUrlTXT")!=null){
			pane.getTfIn().setText(RecordStore.getData("fileUrlTXT")+"");
		}else{
			pane.getTfIn().setText("mapswf\4.txt");
		}
	}
	
	//--------
	private function onClickWrite(e : AWEvent) : void {
		var fileUrl : String = pane.getTf().getText();
		RecordStore.setData("fileUrlSWF",fileUrl);
		loadFileSWF(fileUrl);
	}

	private function loadFileSWF(fileUrl : String) : void {
		var l : Loader = new Loader();
		l.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadFileSWFOK);
		l.load(new URLRequest(fileUrl));
	}

	
	private function onLoadFileSWFOK(e : Event) : void {
		var mc : MovieClip = (e.currentTarget as LoaderInfo).loader.content as MovieClip;
		var mc_map:MovieClip = mc.getChildAt(0) as MovieClip;
		
		var sOut:String=writer.writeData(mc_map);
		pane.getTa().setText(sOut);
		//-复制到剪切板
		System.setClipboard(pane.getTa().getText());
	}
	
	//--------
	private function onClickRead(e : AWEvent) : void {
		var fileUrl : String = pane.getTfIn().getText();
		RecordStore.setData("fileUrlTXT",fileUrl);
		loadFileTXT(fileUrl);
	}

	private function loadFileTXT(fileUrl : String) : void {
		var l : URLLoader = new URLLoader();
		l.addEventListener(Event.COMPLETE, onLoadFileTXTOK);
		l.load(new URLRequest(fileUrl));
	}

	
	private function onLoadFileTXTOK(e : Event) : void {
		var l:URLLoader=e.currentTarget as URLLoader;
		var sOut:String=reader.readData(l.data as String);
		pane.getTaIn().setText(sOut);
		
	}
	
}
}
